﻿using System;
using System.Text.RegularExpressions;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;

namespace BrandonHaynes.Providers.Navigation
	{
	static class TemplateExtensions
		{
		/// <summary>
		/// Returns true when a tab's PageHeadText matches an template-menu identification pattern; otherwise false
		/// </summary>
		public static bool IsTemplatedMenu(this TabInfo tab, string identificationPattern)
			{
			return tab != null ?
				Regex.IsMatch(tab.PageHeadText, identificationPattern, RegexOptions.IgnoreCase) :
				false;
			}

		/// <summary>
		/// Returns the name of any specified custom template, or null when none is specified
		/// </summary>
		public static string GetCustomTemplateName(this TabInfo tab, string identificationPattern, string providerPath)
			{
			var matches = tab != null ?
				Regex.Match(tab.PageHeadText, identificationPattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture) : null;

			return matches != null && matches.Success && matches.Groups["template"] != null && !string.IsNullOrEmpty(matches.Groups["template"].Value) ?
				ResolveTemplateUrl(matches.Groups["template"].Value, providerPath) : null;
			}

		/// <summary>
		/// Given a template name, resolves path tokens (e.g. skin or portal) into a fully-qualified path
		/// </summary>
		private static string ResolveTemplateUrl(string customTemplateName, string providerPath)
			{
			const string prefixPattern = "^(?:(?<pathType>skin|portal):)?(?<template>.*)";
			string qualifiedTemplateName;
			var matches = Regex.Match(customTemplateName, prefixPattern, RegexOptions.IgnoreCase);
			var pathType = matches.Groups["pathType"].Value;
			var templateName = matches.Groups["template"].Value;

			if (pathType.Equals("skin", StringComparison.OrdinalIgnoreCase))
				qualifiedTemplateName = PortalController.GetCurrentPortalSettings().ActiveTab.SkinPath + templateName;
			else if (pathType.Equals("portal", StringComparison.OrdinalIgnoreCase))
				qualifiedTemplateName = PortalController.GetCurrentPortalSettings().HomeDirectory + templateName;
			else
				qualifiedTemplateName = providerPath + templateName;

			return qualifiedTemplateName.Replace("..", string.Empty);
			}
		}
	}
